<?php


namespace App\Common;


use App\Models\AuthModel;
use App\Models\AuthNodeModel;
use App\Models\NodeModel;
use App\Models\UserModel;
use EasySwoole\Component\Singleton;


class AuthService
{
    use Singleton;

    /**
     * 判断是否有权限访问该节点
     * @param $node
     * @param $user_id
     * @return bool
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function checkNode($node, $user_id)
    {
        //判断当前登录是否为超级管理员
        if ($user_id == 1) return true;
        //判断是否加入RABC控制
        $is_auth = NodeModel::create()->where(['node' => $node, 'is_auth' => 1])->get();
        if (empty($is_auth)) return true;
        //获取当前用户角色组信息 ,拆表
        $userAuthData = UserModel::create()->where(['id' => $user_id, 'status' => 1, 'is_deleted' => 0])->field('auth_id')->findOne();
        //解析用户权限
        $auth_id_list = json_decode($userAuthData['auth_id'], true);
        //判断是否有权限访问
        foreach ($auth_id_list as $k => $val) {
            // 判断是否有这个角色权限
            $res = AuthModel::create()->where(['id' => $val, 'status' => 1])->findOne();
            if (!empty($res)) {
                if ($val == 0) return true; //超级管理员组权限
                $is_auth_node = AuthNodeModel::create()->where(['auth' => $val, 'node' => $is_auth['id']])->findOne();
                if (!empty($is_auth_node)) return true;
            }
        }
        return false;
    }

}
